public without sharing class PartRequirePlanController {

	public String backId {get; private set;} 
	public String msg {get; private set;} 
	public Boolean isErr {get; private set;} 
	public String dataJson {get; private set;} 
	public String saveJson {get;  set;} 
	public String searchJson {get;  set;} 
	public Boolean isSuccess {get ; private set;}
    private String sealflag ; 
    public  String comcode {get;private set;}
    public class ControllerException extends Exception {}
    public PartRequirePlanController() {
        
    }
    public void init(){
    	backId = System.currentPageReference().getParameters().get('id');
    	try {
    	    
    	    if(backId == null)setError('页面打开错误!');
    	    if(Id.valueOf(backId).getSobjecttype() != EngineeringPartsRequirementPlanning__c.SObjectType)setError('页面打开错误!');

    	   EngineeringPartsRequirementPlanning__c eprp  =  [select  Id,Status__c ,DemandOrganization__c from  EngineeringPartsRequirementPlanning__c  where Id=: backId];
            
    	   if(eprp.Status__c == '审批中' || eprp.Status__c == '审批成功' )setError('工程配件需求计划申请单'+eprp.Status__c +',不能修改!');
    	   Map<String,Object> dataMap = new Map<String ,Object>();
           comcode = ImportObject.getPicklistValues('EngineeringPartsRequirementPlanning__c', 'DemandOrganization__c', true).get(eprp.DemandOrganization__c);
           
    	   dataMap.put('detail',getDetails());
    	   dataMap.put('searchObject',getSearchObject());
    	   System.debug('PartRequirePlanController==>'+dataMap);
    	   dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap), 'UTF-8');
           String company = [select subCompany__c  from User where Id =:UserInfo.getUserId()].subCompany__c;
           sealflag  =  'Y-'+ ImportObject.getPicklistValues('Contract__c','Corpcode__c',false).get(company);
    	}catch (Exception e) {
    	    ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()));
    	}

    }
    //获取明细
    private List<EPRDBean>  getDetails(){
      	List<EPRDBean> tmp = new List<EPRDBean>();
      	for(EngineeringPartsRequirementDetails__c eprpd : [select Id , Product__c , OrderAmount__c,
      		Product__r.Brand__c,Product__r.Spec__c,Product__r.SerialNo__c,Product__r.NCCode__c,Product__r.ProductName__c  
      	 from EngineeringPartsRequirementDetails__c where EngineeringPartsRequirementPlanning__c =:backId]){
      		tmp.add(new EPRDBean(eprpd));
      	}
      	return tmp ;

    }
    public void search(){

    	Map<String,Object> searchMap = (Map<String,Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));

    	String sql = ' select Id ,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c ,Category1__c ,SealCompany__c from Product__c where  Createddate != null and Company__c like \'%'+comcode+'%\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('ProductName__c'))) == false) sql += ' and ProductName__c like \'%'+DataUtil.getStringValue(searchMap.get('ProductName__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Brand__c'))) == false) sql += ' and Brand__c like \'%'+DataUtil.getStringValue(searchMap.get('Brand__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Spec__c'))) == false) sql += ' and Spec__c like \'%'+DataUtil.getStringValue(searchMap.get('Spec__c'))+'%\' ';

    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('SerialNo__c'))) == false) sql += ' and SerialNo__c like \'%'+DataUtil.getStringValue(searchMap.get('SerialNo__c'))+'%\' ';
 
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category0__c'))) == false) sql += ' and Category0__c like \'%'+DataUtil.getStringValue(searchMap.get('Category0__c'))+'%\' ';
        if(String.isBlank(DataUtil.getStringValue(searchMap.get('Category1__c'))) == false) sql += ' and Category1__c like \'%'+DataUtil.getStringValue(searchMap.get('Category1__c'))+'%\' ';
    	if(String.isBlank(DataUtil.getStringValue(searchMap.get('NCCode__c'))) == false) sql += ' and NCCode__c like \'%'+DataUtil.getStringValue(searchMap.get('NCCode__c'))+'%\' ';

    	sql += ' limit 200 ';
    	List<EPRDBean> tmp = new List<EPRDBean>();
    	for(Product__c p: Database.query(sql)){
            if(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)) continue; 
    		tmp.add(new EPRDBean(p));
    	}

    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }

    private Map<String,List<DataUtil.FieldBean>> getSearchObject(){
    	Map<String,List<DataUtil.FieldBean>> searchMap = new Map<String,List<DataUtil.FieldBean>>();

    	Map<String,DataUtil.FieldBean>proMap = DataUtil.getFieldsInfo(Product__c.SObjecttype, new Set<String>{'ProductName__c','Brand__c','Spec__c','SerialNo__c','Category0__c','Category1__c','NCCode__c'} );
    	searchMap.put('Product__c', proMap.values());
    	return searchMap;
    }

    public void save(){
    	msg = '';
    	List<Object> saveList = (List<Object> ) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson,'UTF-8'));

    	if(saveList.size() == 0 ){
    		msg = '没有数据!';
    		return ; 	
    	}
    	List<EngineeringPartsRequirementDetails__c> eprdList = new List<EngineeringPartsRequirementDetails__c>();
    	for(Object o : saveList){
    		Map<String,Object> mo = (Map<String,Object>) o  ; 
    		EngineeringPartsRequirementDetails__c eprd = new EngineeringPartsRequirementDetails__c();
    		eprd.EngineeringPartsRequirementPlanning__c  =  backId ; 
    		eprd.Product__c = DataUtil.getStringValue(mo.get('productId'));
    		eprd.OrderAmount__c = DataUtil.getDecimalValue(mo.get('amount')) ;
    		eprdList.add(eprd);
    	}
    	SavePoint sp = Database.setSavepoint();
    	try {
    	    delete [select Id from EngineeringPartsRequirementDetails__c where EngineeringPartsRequirementPlanning__c =:backId];
    	    if(eprdList.size() > 0) insert eprdList;
    	    msg = '保存成功!';
    	    isSuccess = true; 
    	}
    	catch (Exception e) {
    		Database.rollback(sp);
    	    msg = '保存失败!'+e.getMessage();

    	}
    	
    }

    @RemoteAction
    public static List<EPRDBean>  matchProduct(List<String> nccodes,String company  ){
    	List<EPRDBean> tmp = new List<EPRDBean>();
    	company = '%'+company+'%';
    	for(Product__c p : [select Id,ProductName__c ,SerialNo__c , Brand__c ,Spec__c,Category0__c,NCCode__c,Category1__c 
    	 from Product__c where NCCode__c in: nccodes and Company__c like:company]){
    		tmp.add(new EPRDBean(p));
    	}
    	return tmp; 
    }

    public void setNil(){
    	dataJson = '{}';
    	saveJson = '[]';
    	searchJson = '{}';
    }
    //设置错误
    private void setError(String message){
    	isErr = true;
      throw new ControllerException(message);

    }

    public class EPRDBean{
    	public String productName ; 
    	public String productId ; 
    	public String nccode ; 
    	public String spec ; 
    	public String serialno ; 
    	public String brand ; 
    	public Decimal amount ; 
    	public String cate0;
        public String cate1;
    	public EPRDBean(EngineeringPartsRequirementDetails__c erpd ){
    		productName = erpd.Product__r.ProductName__c ; 
    		productId = erpd.Product__c;
    		nccode = erpd.Product__r.NCCode__c;
    		spec = erpd.Product__r.Spec__c;
    		serialno = erpd.Product__r.SerialNo__c;
    		brand = erpd.Product__r.Brand__c;
    		amount = erpd.OrderAmount__c; 

    	}
    	public EPRDBean(Product__c erpd ){
    		productName = erpd.ProductName__c ; 
    		productId = erpd.Id;
    		nccode = erpd.NCCode__c;
    		spec = erpd.Spec__c;
    		serialno = erpd.SerialNo__c;
    		cate0  = erpd.Category0__c; 
            cate1 = erpd.Category1__c; 
    		brand = erpd.Brand__c;

    	}
    }



}